#include "time.h"

engine::core::Time::Time()
{
	m_lastTime = SDL_GetTicks64();
	m_frame_start = m_lastTime;
}

engine::core::Time::~Time()
{
    
}

void engine::core::Time::update()
{
    m_frame_start = SDL_GetTicks64();
    double currentTime = static_cast<double>(m_frame_start - m_lastTime) / 1000000000.0;

    if (m_target_frame_time > 0.0)
    {
        limitFrameRate(currentTime);
    }
    else
    {
        m_deltaTime = currentTime;
    }
    m_lastTime = SDL_GetTicks64();
}

float engine::core::Time::getDeltaTime() const
{
    return static_cast<float>(m_deltaTime* m_timeScale);
}

float engine::core::Time::getUnscaledDeltaTime() const
{
    return static_cast<float>(m_deltaTime);
}

float engine::core::Time::getTimeScale() const
{
    return static_cast<float>(m_timeScale);
}

void engine::core::Time::setTimeScale(float scale)
{
    if (scale > 0.0f)
    {
        m_timeScale = static_cast<double>(scale);
    }
    else
    {
        m_timeScale = 1.0; 
	}
}

float engine::core::Time::getTargetFPS() const
{
	return static_cast<float>(m_target_fps);
}

void engine::core::Time::setTargetFPS(int fps)
{
    m_target_fps = fps;
    if (fps > 0)
    {
        m_target_frame_time = 1.0 / static_cast<double>(fps);
    }
    else
    {
        m_target_frame_time = 0.0; 
	}
}

void engine::core::Time::limitFrameRate(float current_delta_time)
{
    if (current_delta_time < m_target_frame_time)
    {
		double sleep_time = m_target_frame_time - current_delta_time;
		Uint64 wait_time = static_cast<Uint64>(sleep_time)*1000000000.0;
		SDL_Delay(wait_time);
		m_deltaTime = static_cast<double>(SDL_GetTicks64()- m_lastTime)/1000000000.0;
    }
}
